<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@include file="/common/global.jsp"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="format-detection" content="telephone=no">
<meta http-equiv="Expires" CONTENT="-1">
<meta http-equiv="Cache-Control" CONTENT="no-cache">
<meta http-equiv="Pragma" CONTENT="no-cache">
<link href="${ctxPath}/static/css/ectouch.css" rel="stylesheet" type="text/css" />
<link href="${ctxPath}/static/css/style2.css" rel="stylesheet" type="text/css" />
<link href="${ctxPath}/static/css/font-awesome.min.css" rel="stylesheet"   type="text/css"/>
<link href="${ctxPath}/static/css/common.css" rel="stylesheet" type="text/css" />
<link href="${ctxPath}/static/fonts/iconfont.css" rel="stylesheet" type="text/css" />
<%@include file="/common/head.jsp"%>
<title><spring:message code="sw.page.order.submit.name"/></title>
</head>
<body>
<script type="text/javascript">
    function validate(o){
        var $this = o.length > 0 ? o: $(o);
        logger.info(o);
        console.log($this);
        console.log($this.val());
        if (!$this.val()) {
            var tip = '请输入'+$this.attr('message');
            layer.msg(tip,{time:1000});
            return '['+tip+']';
        }
        var name = $this.attr('name');
        if ('phoneNo' == name) {
            if(!(/^1[34578]\d{9}$/.test($this.val()))){
                var tip = '输入的手机号有误';
                layer.msg(tip,{time:2000,anim:4,btn:['确定','取消']});
                return tip;
            } else {
                var $smsCode = $("#smsCode");
                if ($smsCode.val()) {
                    if (!$('#originPrice').html()) {
                        // 异步请求折扣.
                        $.ajax({
                            url:'${ctxPath}/busiOrder/disQuery',
                            type:'POST',
                            data:{"totalAmount":$('#totalAmount').attr('totalAmount'),"phoneNo":$('#phoneNo').val(),"smsCode":$('#smsCode').val()},
                            dataType:'JSON',
                            success:function(data){
                                console.log(data);
                                if (data) {
                                    if (data.status == '200') {
                                        var disTotalPrice = data.data;
                                        $('#totalAmount').html(Math.round(Number(disTotalPrice))+"");
                                        $('#originPrice').html('(原价:'+$('#totalAmount').attr('totalAmount')+')');
                                        // 解锁提交按钮.
                                        $('#submitOrder').prop('disabled','false');
                                    } else {
                                        layer.msg(data.msg, {time:2000,btn:['确认','取消']});
                                    }
                                }
                            },
                            error:function(msg){
                                console.log('出错了!');
                                console.log(msg);
                                document.write(msg.responseText);
                            }
                        });
                    }
                }
            }
        }
        if ('smsCode' == name) {
            var $phoneNo = $("#phoneNo");
            if ($phoneNo.val()) {
                if (!$('#originPrice').html()) {
                    // 异步请求折扣.
                    $.ajax({
                        url:'${ctxPath}/busiOrder/disQuery',
                        type:'get',
                        data:{"totalAmount":$('#totalAmount').attr('totalAmount'),"phoneNo":$('#phoneNo').val(),"smsCode":$('#smsCode').val()},
                        dataType:'JSON',
                        success:function(data){
                            console.log(data);
                            if (data) {
                                if (data.status == '200') {
                                    var disTotalPrice = data.data;
                                    $('#totalAmount').html(Math.round(Number(disTotalPrice))+"");
                                    $('#originPrice').html('(原价:'+$('#totalAmount').attr('totalAmount')+')');
                                    // 解锁提交按钮.
                                    $('#submitOrder').removeAttr("disabled");//将按钮可用
                                } else {
                                    layer.msg(data.msg, {time:2000,btn:['确认','取消']});
                                }
                            }
                        },
                        error:function(msg){
                            console.log('出错了!');
                            console.log(msg);
                            document.write(msg.responseText);
                        }
                    });
                }
            }
        }
    }

    function calcDiscount(e)
    {
        var keynum;
        var keychar;
        if(window.event) // IE
        {
            keynum = e.keyCode
        }
        else if(e.which) // Netscape/Firefox/Opera
        {
            keynum = e.which
        }

        logger.info(keynum);
        // keychar = String.fromCharCode(keynum)
        var $phoneNo = $("#phoneNo");
        var $smsCode = $("#smsCode");
        logger.info("手机号:{0}-验证码:{1}".format($phoneNo.val(),$smsCode.val()));
        if ($phoneNo.val() && $smsCode.val()) {
            if ($phoneNo.val().length == 11 && $smsCode.val().length >= 6) {
                if (!$('#originPrice').html()) {
                    logger.info("---开始异步请求---");
                    // 异步请求折扣.
                    $.ajax({
                        url:'${ctxPath}/busiOrder/disQuery',
                        type:'get',
                        data:{"totalAmount":$('#totalAmount').attr('totalAmount'),"phoneNo":$('#phoneNo').val(),"smsCode":$('#smsCode').val()},
                        dataType:'JSON',
                        success:function(data){
                            console.log(data);
                            if (data) {
                                if (data.status == '200') {
                                    var disTotalPrice = data.data;
                                    $('#totalAmount').html(Math.round(Number(disTotalPrice))+"");
                                    $('#originPrice').html('(原价:'+$('#totalAmount').attr('totalAmount')+')');
                                    // 解锁提交按钮.
                                    $('#submitOrder').removeAttr("disabled");//将按钮可用
                                } else {
                                    layer.msg(data.msg, {time:2000,btn:['确认','取消']});
                                }
                            }
                        },
                        error:function(msg){
                            console.log('出错了!');
                            console.log(msg);
                            document.write(msg.responseText);
                        }
                    });
                    logger.info("---异步请求结束---");
                }
            }
        }

    }

    /**
     *  判断orderToken是否存在.
     * */
    function judgeOrderTokenIsExsit(){
        $.ajax({
            url:'${ctxPath}/busiOrder/orderToken',
            type:'POST',
            dataType:'json',
            success:function(data){
                logger.info({data:data, pageName:'order_confirm.jsp', groupName:'---异步判断OrderToken---', desc:'判断是否是重复订单'});
                if (data) {
                    if (data.status == '200') {
                        // do nothing ...
                    } else if (data.status == '400') {
                        // 引导用户到首页.
                        layer.msg('请重新下单!即将跳回首页...',{time:2000,btn:['确定','取消']});
                        logger.info(data.msg);
                        setTimeout(function () {
                             window.location.href = '${ctxPath}/home/index';
                        },"2000");
                    }
                }
            },
            error:function(msg){
                if (msg) {
                    logger.info({data:msg, pageName:'order_confirm.jsp', groupName:'---这里是异常---', desc:''});
                }
            }
        });
    }

    function makeSelect2(o){
        $(o).select2({
            placeholder: "请至少选择一个",
            tags:true,
            createTag:function (decorated, params) {
                return null;
            },
            // allowClear: true,
            width:'256px'
        });
    }
</script>
<div class="Layout_style">
 <%--<header id="header">
  <div class="header_l header_return"><a href="javascript:;" onclick="javascript :history.back(-1);" class="return_cz"><i class="fa fa-angle-left icon_zjt"></i></a></div>
  <h1> <spring:message code="sw.page.order.submit.name"/></h1>
  <div class="header_r"> <a class="iconfont icon-icon4" href="user.html"> </a></div>
</header>--%>
<section class="user_style">
<div class="shop_cart">
   <div class="schedule"><%--<ul><li><em>1</em>查看购物车</li><li class="on"><em>2</em>确认订单</li><li><em>3</em>成功提交订单</li></ul>--%></div>
</div>
 <div class="user_info_style Submit_Order">
      <div class="Order_address">
         <span class="address_title">收货地址</span>
          <c:if test="${!empty devMode}">
              ${devMode}
          <hr>
          ${from}
          <hr>
          ${staticServer}
          </c:if>
          <%--先禁用编辑按钮--%>
         <%--<a href="#" class="fa fa-pencil-square-o modify"></a>--%>
        <div class="address_info">
            <%--<form id="theForm" role="form" action="/" method="POST">--%>
            <form id="theForm" role="form" action="${ctxPath}/busiOrder/confirm" method="POST">
            <div class="form-group">
            <p>    <label for="province">省</label>:<select id="province" name="" message="省">
                <option value="">请选择</option>
            </select>
            </p>
            <p>
                <label for="city">市:</label><select id="city" name="" message="市">
                <option value="">请选择</option>
            </select>
            </p>
            <p>
                <label for="region">区:</label><select id="region" name="" message="区">
                <option value="">请选择</option>
            </select>
            </p>

            <input id="areaId" type="hidden" name="areaId" value=""/>
            <input type="hidden" name="orderToken" value="${orderToken}"/>
            <c:if test="${!empty product}">
                <input type="hidden" name="from" value="productDetail"/>
                <input type="hidden" name="productId" value="${product.id}"/>
                <input id="sum" type="hidden" name="sum" value=""/>
            </c:if>
            <c:if test="${!empty cartvo}">
                <input type="hidden" name="from" value="cart"/>
                <input type="hidden" name="cartId" value="${cartvo.id}"/>
                <input type="hidden" name="cartItemIds" value="${cartItemIds}"/>
            </c:if>
            <p><font color="red">*</font> <label for="address">详细地址</label><input id="address" name="address" message="详细地址" style="width:70%" value="" class="form-control required" onblur="validate(this)"/></p>
            <p><font color="red">*</font> <label for="receiverName">收货人姓名</label><input id="receiverName" name="receiverName" message="收货人姓名" value="" class="form-control required" onblur="validate(this)"/></p>
            <p><font color="red">*</font> <label for="phoneNo">收货人联系方式</label><input id= "phoneNo" name="phoneNo" message="收货人联系方式" value="" class="form-control required" onblur="validate(this)" onkeyup="this.value=this.value.replace(/\D/g,''); return calcDiscount(event);" onafterpaste="this.value=this.value.replace(/\D/g,'');"<%--onkeydown="return calcDiscount(event);"--%>/></p>
                <div><font color="red">*</font> <label for="smsCode">短信验证码</label><br>
                    <div style="float:left;">
                    <input id= "smsCode" name="smsCode" message="短信验证码" value="" class="form-control required" onblur="validate(this)" <%--onkeyup="this.value=this.value.replace(/\D/g,'')"--%> onkeyup="this.value=this.value.replace(/\D/g,'');return calcDiscount(event);" onafterpaste="this.value=this.value.replace(/\D/g,'');" <%--onkeydown="return calcDiscount(event);"--%>/>
                    </div>
                    <div><button id="smsCodeBtn" type="button" class="btn btn-primary">获取验证码</button></div>
                </div>
          </div>
          </form>
      </div>
      <div class="p_list Order_p_list"><hr>

  <c:if test="${from eq 'productDetail'}">
     <ul class="list list_name">
        <%--<em class="lable_icon"><i class="text-name">预售</i></em>--%>
        <li class="img"><a href="${ctxPath}/busiProduct/do_detail_Page?id=${bs.id}"><img src="${staticServer}/${product.imgUrl}" width="100%" height="100%"></a></li>
        <li class="p_list_one">
        <a href="#">
            <div <%--style="border:1px goldenrod solid;"--%>>
                <p class="p_title" style="/*border:1px solid;*/padding:0px;margin-bottom:0px;">${product.zhName}</p>
                <p class="Brief " style="/*border:1px solid;*/padding:0px;margin-bottom:0px;line-height:20px">${product.prodDesc}</p>
                <div style="/*border:1px red solid;*/height:20px;width:auto;margin-top:0px;">
                    <div style="float:right;/*border:1px green solid;*/height:20px;width:100px;"><p><span style="color:#FF0000;">￥<fmt:formatNumber value="${product.disPrice}" type="currency" pattern="#.##"/>元</span><span style="color:#CCCCCC; text-decoration: line-through; padding-left:5px;">￥<fmt:formatNumber value="${product.price}" type="currency" pattern="#.##"/>元</span></p></div>
                </div>
            </div>
          <%--  数量：1--%>
<%--            数量：<input type="text" class="spinner" name="sum" value=""/>--%>
        </a>
       </li>
      </ul>
      <div id="datePlugin"></div>
      <div class="Order_price">总价：<span id="totalAmount" totalAmount="<fmt:formatNumber value="${product.price}" type="currency" pattern="#.##"/>"><fmt:formatNumber value="${product.price}" type="currency" pattern="#.##"/></span>元<font id="originPrice" color="gray"></font></div>

  </c:if>

  <c:if test="${ from eq 'cart'}">
      <c:forEach items="${cartvo.cartItems}" var="item">
      <ul class="list list_name">
          <li class="img "><a href="product_detailed.html"><img src="${staticServer}/${item.standy1}"></a></li>
          <li class="p_list_one">
              <a href="#">
                  <a href="#">
                  <p class="p_title">${item.prodName}</p>
                  <p class="Brief ">${item.standy2}</p>
                  <%--<p class="p_Price">￥<fmt:formatNumber value="${item.prodPrice}" type="currency" pattern="#.##"/>元<c:if test="${!empty item.sum}">x${item.sum}</c:if><span>${item.standy4}元</span></p>--%>
                      <div style="/*border:1px red solid;*/height:20px;width:auto;margin-top:0px;">
                          <div style="float:right;/*border:1px green solid;*/height:20px;width:150px;"><p><p style="color:#FF0000;">￥<fmt:formatNumber value="${item.prodPrice}" type="currency" pattern="#.##"/>元<c:if test="${!empty item.sum}">x${item.sum}</c:if><span style="color:#CCCCCC; text-decoration: line-through; padding-left:5px;">${item.standy4}元</span></p></div>
                      </div>
              </a>
          </li>
      </ul>
      </c:forEach>
      <div id="datePlugin"></div>
      <div class="Order_price">总价：<span id="totalAmount" totalAmount="<fmt:formatNumber value="${cartvo.totalAmount}" type="currency" pattern="#.##"/>"><fmt:formatNumber value="${cartvo.totalAmount}" type="currency" pattern="#.##"/></span>元<font id="originPrice" color="gray"></font></div>
  </c:if>
      <%--<div class=""><a href="javascript:void(0)" class="c-btn3" id="submitOrder" from="${from}">提交并支付订单</a></div>--%>
      <button type="button" class="btn btn-success" style="width:100%;" id="submitOrder" from="${from}" disabled="true">提交并支付订单</button>
      <%--<ul class="list list_name">
    <li class="img "><a href="product_detailed.html"><img src="products/p_9.jpg"></a></li>
    <li class="p_list_one">
    <a href="#">
    <p class="p_title">巴黎欧莱雅男士洗面膜</p>
	<p class="Brief ">抗生素的理想替代品，安全、环保，低污染</p>
	<p class="p_Price">￥30.00元<span>40.00元</span></p>
    </a>
   </li>
  </ul>--%>
  <%--<div class="Delivery_time">选择送货时间：<span class="Delivery_timebtn" id="endTime">默认</span></div>--%>
 <%-- <div id="datePlugin"></div>
  <div class="Order_price">总价：345.5元</div>
   <div class=""><a href="javascript:ovid()" class="c-btn3" id="submitOrder">提交并支付订单</a></div>
  </div> --%>
 </div>
</section>
</div>
<script src="${ctxPath}/static/js/TouchSlide.1.1.source.js" type="text/javascript"></script>
<script type="text/javascript" src="${ctxPath}/static/js/iscroll.js" ></script>
<script type="text/javascript" src="${ctxPath}/js/date.js" ></script>

<%@include file="/common/footer.jsp"%>
<%@include file="/common/tooltip.jsp"%>


<script type="text/javascript">

    var commonFun = {
      constant:{
          PROVINCE_REGION_LEVEL:2,
          CITY_REGION_LEVEL:3,
          AREA_REGION_LEVEL:4
      },
      getRegionDataByParentId: function(parentId, regionLevel){
          var param = null;
          if (parentId) {
              param = {'parentRegionId':parentId, 'regionLevel':regionLevel};
          } else {
              param = {'regionLevel':regionLevel};
          }

         return $.ajax({
              url:'${ctxPath}/alRegion/dataGrid',
              type:'POST',
              dataType:'JSON',
              data: param,
              async:false,
              success:function(data){
                  logger.info({pageName:'order_confirm.jsp', data:data, groupName:'----友情分割线----'});
              },
              error:function(data){
                  logger.error(data);
              }
          }).responseText;
      },
      getRegionDataByParentIdNew: function(id, parentId, regionLevel){
          var param = null;
          if (parentId) {
              param = {'parentRegionId':parentId, 'regionLevel':regionLevel};
          } else {
              param = {'regionLevel':regionLevel};
          }
          $("#"+id).select2({
              ajax: {
                  url: "${ctxPath}/alRegion/dataGridNew",
                  dataType: 'json',
                  delay: 250,
                  data: param,
                  processResults: function (data, params) {
                      // parse the results into the format expected by Select2
                      // since we are using custom formatting functions we do not need to
                      // alter the remote JSON data, except to indicate that infinite
                      // scrolling can be used
                      params.page = params.page || 1;

                      return {
                          results: data.items,
                          pagination: {
                              more: (params.page * 30) < data.total_count
                          }
                      };
                  },
                  cache: true
              },
              escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
              minimumInputLength: 1//,
              //templateResult: formatRepo, // omitted for brevity, see the source of this page
              //templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
          });
      }
  }

  var regionObj = {
      init:function(id, parentId, regionLevel){
          logger.info('开始初始化...');
          // commonFun.getRegionDataByParentIdNew(id, parentId, regionLevel);
          var retStr = commonFun.getRegionDataByParentId(parentId, regionLevel);
          logger.info(retStr);
          var data = $.parseJSON(retStr);
           if (null != data && data.status == 200) {
               logger.info(data.data instanceof Array);
               if (data.data instanceof Array) {
                    var items  = data.data;
                   $('#'+id).append('<option value="" selected>请选择</option>');
                    for (var i = 0; i < items.length; i ++) {
                        var item = items[i];
                        logger.info(item);
                        $('#'+id).append('<option value="{0}" parentId="{2}">{1}</option>'.format(item.regionId, item.regionName, item.parentRegionId));
                    }
               }
           } else if (data.status == 400){
                console.log("请求失败!");
           }
          logger.info('初始化结束...');


      }
  }

  $(function(){

      judgeOrderTokenIsExsit();

      //处理产品描述过长，影响页面布局。
      $(".Brief").each(function(){
          var desc = $(this).html();
          var length = desc.length;
          //标签内容字符长度超过40
          if( length> 25 ){
              //截取内容
              desc = desc.substr(0,20)+"......";
          }
          $(this).html(desc);
      });

      // 启用Jquery校验器
      $("#theForm").validate();
      // 启用select2框
      makeSelect2('#province');
      makeSelect2('#city');
      makeSelect2('#region');
      // 启用数字加减插件
     /* $('.spinner').spinner();*/


      // 1、初始化省
      regionObj.init('province', null, commonFun.constant.PROVINCE_REGION_LEVEL);
      // 2、省注册change事件
      $('#province').change(function(){
          logger.info({data:$(this).val(), desc:'选择省'});
          // $('#city').select2("val",""); // 这个方法有性能问题.
          $('#city').val('');
          $('#city').empty();
          $('#select2-city-container').html('');
          // $('#region').select2("val","");
          $('#region').val('');
          $('#region').empty();
          $('#select2-region-container').html('');
          regionObj.init('city', $(this).val(), commonFun.constant.CITY_REGION_LEVEL);
      });
      // 3、市注册change事件
      $('#city').change(function(){
          logger.info({data:$(this).val(), desc:'选择市'});
          // $('#region').select2("val","");
          $('#region').val('');
          $('#region').empty();
          $('#select2-region-container').html('');
          regionObj.init('region', $(this).val(), commonFun.constant.AREA_REGION_LEVEL);
      });

      $('#smsCodeBtn').click(function(){
          logger.info({data:'你点了获取短信验证码!', groupName:'----短信验证码分割线----'});
          if(validate($('#theForm input[name="phoneNo"]'))){ return; };
          $.ajax({
              url:'${ctxPath}/common/smsCode',
              type:'GET',
              data:{'phoneNo': $('#theForm input[name="phoneNo"]').val()},
              dataType:'json',
              success:function(data){
                  logger.info({data:data, groupName:'-----感情不是你想买就能买----'});
                  if (data) {
                      if ( data.status == '200') {
                          layer.msg('验证码已发送至您的手机!请注意查收!',{time:5000,anim:4,btn:['确认','取消']});
                      } else if ( data.status == '400' ){
                          layer.msg('短信发送失败!请稍后再试!',{time:5000,anim:4,btn:['确认','取消']});
                      } else if ( data.status == '406' ) {
                          layer.msg('手机号不能为空!',{time:5000,anim:4,btn:['确认','取消']});
                      }
                  }
              },
              error:function(errorMessage){
                  console.group('----这里是异常!----');
                  logger.info(errorMessage);
                  console.groupEnd();
              }
          });
      });

      $("#submitOrder").click(function () {
          layer.confirm('是否提交并支付订单?',{
              title: ['提示框','background-color:#8DCE16; color:#fff;'],
              btn: ['确认','取消'],
              yes: function(){
                  if(validate($('#province'))){ return; };
                  if(validate($('#city'))){ return; };
                  if(validate($('#region'))){ return; };
                  if(validate($('#theForm input[name="address"]'))){ return; };
                  if(validate($('#theForm input[name="receiverName"]'))){ return; };
                  if(validate($('#theForm input[name="phoneNo"]'))){ return; };
                  if(validate($('#theForm input[name="smsCode"]'))){ return; };
                  $("#areaId").val($("#region").val());
                  $("#sum").val("1");// 先默认设置为1吧
                  $('#theForm').submit();
                  layer.close();
                  layer.load(1, {
                      shade: [0.1,'#fff'] //0.1透明度的白色背景
                  });
              },
              cancel:function(){
                  // do nothing...
              }
          });

      });
  });
</script>
</body>
</html>
